package xna.android.Telas;

import java.util.ArrayList;
import java.util.Random;
import java.util.Iterator;
import java.util.List;

import xna.android.Enemy;
import xna.android.Explosion;
import xna.android.Game1;
import xna.android.GameController;
import xna.android.SoundManager;
import xna.android.SpriteFont;
import xna.android.Tiro;
import xna.android.Utils.SpriteAnimated;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceView;
import br.com.R;

public class Jogo extends SurfaceView 
{
	private static final String TAG = Jogo.class.getSimpleName();

	private SpriteAnimated hero;
	
	private Enemy enemy;

	private Explosion explosion;
	
	private static final int EXPLOSION_SIZE = 200;

	private SpriteFont spriteFont;

	private SoundManager mSoundManager;
	
	List<Tiro> tiros=new ArrayList<Tiro>();
	
	List<Enemy> inimigos=new ArrayList<Enemy>();

	private GameController gameController; 

	public SoundManager getmSoundManager() 
	{
		return mSoundManager;
	}

	private boolean isPlayingBackGround = false;
	
	public Jogo(Context Content, SoundManager mSoundManager)
	{
		super(Content);
		
		this.mSoundManager = new SoundManager(Content);

		this.mSoundManager.addSound("background", R.raw.background);
		this.mSoundManager.addSound("explosion", R.raw.explosion);

		hero = new SpriteAnimated(BitmapFactory.decodeResource(getResources(), R.drawable.atirando),
				320/2,
				480/2, 
				96,
				96, 
				11,
				11,
				0,
				mSoundManager);
		
		Random randomGenerator = new Random();
		
		for (int i = 0; i < 3; i++) {  // i indexes each element successively.
		
			
			int x = (int) (50 + (Math.random() * 200));  
			int y = (int) (50 + 10* i + (Math.random() * 200));
			
			if (Game1.DEBUG)
			{
			Log.d(TAG, "Criado Enemy" + i + "em x:" + x +" e y:" + y);
			}
				
			inimigos.add(new Enemy(BitmapFactory.decodeResource(getResources(),R.drawable.android),
					x,
					y,
					50,
					50,
					1,
					1,
					this.mSoundManager));
			}

		this.spriteFont = new SpriteFont(BitmapFactory.decodeResource(getResources(), R.drawable.fonte_verde));
		//http://developer.android.com/index.html
		//http://developer.android.com/guide/index.html
		//http://stackoverflow.com/questions/1077357/can-the-android-drawable-directory-contain-subdirectories
		
		gameController = new GameController(Content);
	}

	public void Update(int screenWidth, int screenHeight)
	{
		/*sprite.update(screenWidth, screenHeight);
		sprite2.update(screenWidth, screenHeight);

		if (sprite.intersects(sprite2.getX(), sprite2.getY(), sprite2
				.getBitmap().getWidth(), sprite2.getBitmap().getHeight())&&sprite.isVisible())
		{
			sprite.setVisible(false);

			if (explosion == null || explosion.getState() == Explosion.State.DEAD)
			{
				explosion = new Explosion(EXPLOSION_SIZE, sprite.getX(), sprite.getY() );
				mSoundManager.playSound("explosion");
			}
		}*/		

		hero.update(System.currentTimeMillis());
		
		Iterator<Enemy> ei=inimigos.iterator();
		while(ei.hasNext())
		{
			Enemy e = (Enemy)ei.next();
			e.update(System.currentTimeMillis(), screenWidth, screenHeight);

			Iterator<Enemy> ei2=inimigos.iterator();
			while(ei2.hasNext())
			{
				Enemy e2 = (Enemy)ei2.next();
				if(!e2.equals(e) && e2.intersects(e))
				{
					e2.togglerDirecao();
					e.togglerDirecao();
				}
				
	        }
			
			Iterator<Tiro> it=tiros.iterator();
			while(it.hasNext())
			{
				Tiro v = (Tiro)it.next();
				
				v.update(screenWidth, screenHeight);
				
				if(v.intersects(e))
				{
					e.setPontos(e.getPontos()-20);
					v.setVisible(false);
					Log.d(TAG, "enemy points:" + e.getPontos());
					
				}
				
				if(!v.isVisible())
				{
					it.remove();
				}
	        }
			
        }
		//enemy.update(System.currentTimeMillis(), screenWidth, screenHeight);

		//TODO fazer as explosoes pertecerem ou aos sprites ou aos tiros...
		if (explosion != null && explosion.isAlive())
		{
			explosion.update(((Rect) getHolder().getSurfaceFrame()));
		}
		
		
		if (!isPlayingBackGround)
		{
			isPlayingBackGround = true;
			mSoundManager.playLoopedSound("background");
		}		
	}

	public void Draw(Canvas spriteBatch)
	{
		
		spriteBatch.drawColor(Color.BLACK);
		
		hero.draw(spriteBatch);
		Iterator<Enemy> ei=inimigos.iterator();
		while(ei.hasNext())
		{
          ei.next().draw(spriteBatch);
        }
		//enemy.draw(spriteBatch);

		spriteFont.drawString(spriteBatch, "Escrevendo: X " + ((int)getWidth()-250) + " Y " + ((int)getHeight()-100), ((int)getWidth()-250), ((int)getHeight()-100));

		if (explosion != null)
		{
			explosion.draw(spriteBatch);
		}
		
		Iterator<Tiro> it=tiros.iterator();
		while(it.hasNext())
		{
          it.next().draw(spriteBatch);
        }

		gameController.draw(spriteBatch);
	}

	public boolean onTouchEvent(MotionEvent event) //TODO acrescentar o mesmo width e height do update
	{
		
		if (event.getAction() == MotionEvent.ACTION_DOWN)
		{
			// controle de evento com o sprite
//			sprite.handleActionDown((int) event.getX(), (int) event.getY());
//			sprite2.handleActionDown((int) event.getX(), (int) event.getY());

			// checagem do toque embaixo da tela
			/*if (event.getY() < getHeight() - 50)
			{
				//thread.setRunning(false);
				//TODO
				//((Activity) getContext()).finish();
			} 
			else 
			{
				Log.d(TAG, "Coords: x=" + event.getX() + ",y=" + event.getY());
			}*/
			Log.d(TAG, "Coords: x=" + event.getX() + ",y=" + event.getY());
			
			hero.getmSoundManager().playSound("pistol");
			
			tiros.add(new Tiro(BitmapFactory.decodeResource(
				getResources(), R.drawable.bola), 
				hero.getX() + hero.getSpriteWidth()/2, 
				hero.getY() + hero.getSpriteHeight()/2, 
				mSoundManager, 
				14,14, 1,1, 
				(int)event.getX(), (int)event.getY() ) );
		}

		if (event.getAction() == MotionEvent.ACTION_MOVE)
		{
			
			// gestos
			/*if (sprite.isTouched())
			{
				// tocado!
				sprite.setX((int) event.getX());
				sprite.setY((int) event.getY());
			}

			if (sprite2.isTouched())
			{
				// tocado!
				sprite2.setX((int) event.getX());
				sprite2.setY((int) event.getY());
			}*/

			 
		}

		if (event.getAction() == MotionEvent.ACTION_UP)
		{
			
			// larguei
			/*if (sprite.isTouched())
			{
				sprite.setTouched(false);
			}
			if (sprite2.isTouched())
			{
				sprite2.setTouched(false);
			}*/
			
		}
		
		return true;		
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		hero.onKeyDown(keyCode, event);
		
		switch (keyCode)
		{
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			if(Game1.DEBUG)
			Log.d(TAG, "KEYCODE_DPAD_RIGHT");
			break;
		case KeyEvent.KEYCODE_DPAD_UP:
			if(Game1.DEBUG)
			Log.d(TAG, "KEYCODE_DPAD_UP");
			break;
		case KeyEvent.KEYCODE_DPAD_LEFT:
			if(Game1.DEBUG)
			Log.d(TAG, "KEYCODE_DPAD_LEFT");
			break;
		case KeyEvent.KEYCODE_DPAD_DOWN:
			if(Game1.DEBUG)
			Log.d(TAG, "KEYCODE_DPAD_DOWN");
			break;

		default:
			if(Game1.DEBUG)
			Log.d(TAG, "DEFAULT");
			break;
		}
		return true;
	}
	
	public boolean onKeyUp(int keyCode, KeyEvent event)
	{
		hero.onKeyUp(keyCode, event);
		
		switch (keyCode)
		{
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			if(Game1.DEBUG)
			Log.d(TAG, "KEYCODE_DPAD_RIGHT");
			break;
		case KeyEvent.KEYCODE_DPAD_UP:
			if(Game1.DEBUG)
			Log.d(TAG, "KEYCODE_DPAD_UP");
			break;
		case KeyEvent.KEYCODE_DPAD_LEFT:
			if(Game1.DEBUG)
			Log.d(TAG, "KEYCODE_DPAD_LEFT");
			break;
		case KeyEvent.KEYCODE_DPAD_DOWN:
			if(Game1.DEBUG)
			Log.d(TAG, "KEYCODE_DPAD_DOWN");
			break;

		default:
			if(Game1.DEBUG)
			Log.d(TAG, "DEFAULT");
			break;
		}
		return true;
	}
	
	
}